import { acceptHMRUpdate, defineStore } from "pinia";
// import { userType } from "../types";
import { fetchUpdateToken } from "@/server";

export const useAuthStore = defineStore("auth", {
  state: () => {
    return {
      isAuthenticated: !!localStorage.getItem("token"),
      user: JSON.parse(localStorage.getItem("userInfo") as string),
      token: "",
    };
  },
  getters: {
    getAuthenticated: (state) => state.isAuthenticated,
    getUser: (state) => state.user,
    getToken: (state) => state.token,
  },
  actions: {
    async init(){
      console.log("init");
      const token = localStorage.getItem('token')
      if(token){
        try{
          const data = await fetchUpdateToken(()=>true);
          this.setAuth(true);
          this.setToken(token);
          this.setUser(data);
        }catch{
          this.setAuth(false);
        }
      }
      return      
    },
    setAuth(isAuth: boolean) {
      if (isAuth) {
        this.isAuthenticated = isAuth;
      } else {
        this.isAuthenticated = false;
        this.user = {}
        localStorage.removeItem('userInfo')
        this.token = ''
        localStorage.removeItem("token");
      }
    },
    setUser(user: {} | void) {
      if (user) {
        this.user = user;
        localStorage.setItem("userInfo",JSON.stringify(user));
      } else {
        this.user = {};
        localStorage.removeItem("userInfo");
      }
    },
    setToken(token:string){
      if (token) {
        this.token = token;
        localStorage.setItem("token", token);
      } else {
        this.token = '';
        localStorage.removeItem("token");
      }
    }
  },
});
if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useAuthStore, import.meta.hot));
